<template>
  <div>
    <div class="search-content">
      <el-form
        ref="searchForm"
        :inline="true"
        :model="searchContent">
        <el-form-item label="兑换单号：" prop="point_ordersn">
          <el-input
            class="search-content-input"
            v-model="searchContent.point_ordersn"
            placeholder="兑换单号">
            </el-input>
        </el-form-item>
        <el-form-item label="会员名称：" prop="point_buyername">
          <el-input
            class="search-content-input"
            v-model="searchContent.point_buyername"
            placeholder="会员名称">
            </el-input>
        </el-form-item>        
        <el-form-item label="兑换时间：" prop="order_time">
          <el-date-picker
            v-model="searchContent.order_time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item label prop="point_orderstate" v-if="!externalData">
          <el-select
            clearable
            v-model="searchContent.point_orderstate"
            placeholder="订单状态">
            <el-option
              v-for="item in type_options"
              :key="item.value_txt"
              :label="item.value_txt"
              :value="item.value">
              </el-option>
          </el-select>
        </el-form-item>     
        <el-form-item label prop="结算" v-if="!externalData">
          <el-select
            clearable
            v-model="searchContent.is_settled"
            placeholder="结算状态">
            <el-option value="0" label="未结算"></el-option>
            <el-option value="1" label="已结算"></el-option>
          </el-select>
        </el-form-item>           
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button type="primary" @click="resetSearchData">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="search-list">
      <el-table
        :data="goodsList"
        border
        :height="oHeight"
        :fit="true"
        header-cell-class-name="hdCellStyle" 
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="center"
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="point_ordersn"
          label="兑换单号"
          min-width="140"
          #default="{ row }">
          <span :class="`color-${row.exception_state}`">{{row.point_ordersn}}</span>
          <el-tooltip class="item" effect="dark" content="异常取消" placement="right-start" v-if="row.exception_state == 1">
            <i class="el-icon-question color-1" />
          </el-tooltip>
        </el-table-column>
        <el-table-column
          align="center"
          prop="point_buyername"
          label="手机号"
          min-width="120"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="point_pointnum"
          label="抵扣积分"
          min-width="76"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="point_paynum"
          label="承担商家"
          min-width="80"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="point_shippingfee"
          label="商家承担积分"
          min-width="76"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="point_addtime"
          label="支付时间"
          min-width="130"
          #default="{ row }"
          >{{
            (row.point_addtime * 1000) | dateFormatter("YYYY-MM-DD hh:mm:ss")
          }}</el-table-column
        >
        <el-table-column
          align="center"
          label="订单状态"
          min-width="120"
          #default="{ row }"
        >
       
          {{ row.point_orderstatetext.order_state }}
          <span v-if="row.point_orderstatetext.change_state">{{
            `,${row.point_orderstatetext.change_state}`
          }}</span>
        </el-table-column>
        <el-table-column
          align="center"
          prop="is_settled"
          label="结算状态"
          min-width="80"
          #default="{ row }"
        >
          <span v-if="row.is_settled == 0">未结算</span>
          <span v-else>已结算</span>
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          prop="isInitiative"
          label="操作"
          min-width="280"
          v-if="!externalData"
          #default="{ row }"
        >
          <el-button type="primary" @click="buttonDeal('showOrder', row)">结算</el-button>
          <el-button
            v-show="row.is_bill === '1' && row.is_review === '0'"
            type="primary"
            @click="billRollback(row)">
            撤回
          </el-button>
        </el-table-column>
      </el-table>
      <div class="bottom">
        <div class="btn-group">
          <el-button type="primary" class="btn-bottom" @click="expertData"
            >导出检索数据</el-button
          >
          <el-button type="primary" class="btn-bottom" @click="oneBill" v-if="!externalData"
            >一键结算</el-button
          >
        </div>
        <!--分页部分-->
        <div class="paginationOne">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="searchContent.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="searchContent.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { resize } from "@/common/js/height.js";
import { dateFormatter, objScreen } from "@/common/js/util";
import axios from 'axios'
export default {
	props: {
    externalData: { // 注意此属性不要删除，当此组件被单独引入第三方组件时候的父组件传值属性
			type: Object,
			default: null
		} 
	},
  data() {
    return {
      goodsList: [],
      oHeight: 800,
      searchContent: {
        currentPage: 1,
        pageSize: localStorage.getItem("pageSize") * 1 || 20,
        order_time: "",
        point_ordersn: "",
        point_buyername: "",
        member_mobile: "",
        point_names: "",
        pgoods_business_txt: "",
        category_id: "",
        point_paymentcode: "",
        point_orderstate: "",
        payed: "",
        is_bill: "",
        is_settled: "",
        originate: '',
        is_flash: '',
        is_pt: '',
        is_valid: '',
        exception_state: ''
      },
      originate: '',
      dialogFormVisible: false,
      codeFileList: [],
      searchObj: {},
      total: 0,
      category_options: [],
      type_options: [],
      pgoods_brand_options: [],
      check: [],
      execlErr: [],
      logistics: {
        dialogImportVisible: false,
        fileList: [],
        imageAccept: ['.xlsx', '.xls'],
        rules: {
          fileList: [
              { required: true, message: '请添加导入文件', trigger: 'change' }
          ],
        }
      }
    };
  },
  created() {
    this.getListData();
    this.beforeData();
  },
  methods: {
    // 更新采购商品状态
    handleInnerChange(row) {
      const datas = {
        order_id: row.point_orderid,
        point_inner: row.point_inner_checked ? 1 : 0
      }
      this.$http.post("/admin/pointprod/index.php?act=pointOrder&op=update", datas)
      .then(res => {
        if (res.code == 1) {
          this.$message.success(`${res.msg}`)
        } else {
          row.point_inner_checked = false
          this.$message.error(`${res.msg}`)
        }
      })
    },
    handleLogisticsRemove(files, fileList) {
      this.logistics.fileList = fileList;
    },

    cancelLogistics() {
      this.logistics.dialogImportVisible = false;
      this.$refs.importForm.resetFields();
    },

    beforeData() {
      var data = {
        page: 1,
        pageSize: 99999,
      };
      this.$http
        .get(
          `/admin/pointprod/index.php?act=pointCategory&op=list&parent_id=0`,
          {
            params: data,
          }
        )
        .then((res) => {
          this.category_options = res.data.list;
        })
        .catch((err) => {
          this.$message.error(err);
        });
      this.$http
        .get(`/admin/pointprod/index.php?act=pointOrder&op=stateList`, {
          params: data,
        })
        .then((res) => {
          this.type_options = res.data;
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
      closeIntegral(item) {
      let that = this;
      this.$confirm("确认关闭？")
        .then((res) => {
          this.$http
            .post("/admin/pointprod/index.php?act=pointOrder&op=closePointOrder", {
              pay_ordersn: item.point_ordersn,
            })
            .then((res) => {
              if (res.code == 1) {
                 this.$message.success(res.msg);
                that.getListData(); //刷新列表
              } else {
                alert(res.msg);
              }
            });
        })
        .catch((res) => {
          console.log(res);
        });
    },
    refund(item) {
      let that = this;
      this.$confirm("确认退款？")
        .then((res) => {
          this.$http
            .post("/admin/bill/index.php?act=commonRefund&op=refund", {
              pay_ordersn: item.point_ordersn,
            })
            .then((res) => {
              if (res.code == 1) {
                that.getListData(); //刷新列表
              } else {
                alert(res.msg);
              }
            });
        })
        .catch((res) => {
          console.log(res);
        });
    },
    // 点击编辑
    submitExecl() {
      this.dialogFormVisible = true;
    },
    codeChange(val, list) {
      this.codeFileList = list;
    },
    oneBill(type) {
      let url = "/admin/bill/index.php?act=onlineBill&op=Bill";
      let idArr = [];
      let dataErr = false;
      if (this.check.length === 0) {
        this.$message.warning("请勾选数据");
        return;
      }
      //
      this.check.forEach((item) => {
        if (
          (item.point_orderstate === "30" || item.point_orderstate === "40") &&
          item.is_bill !== "1"
        ) {
          idArr.push(item.point_orderid);
        } else {
          dataErr = true;
        }
      });
      if (dataErr) {
        this.$message.error("请选择正确的状态！");
        return;
      }
      if (type === 1) {
        url = "/admin/bill/index.php?act=onlineBill&op=billRollback";
      }
      this.$http
        .post(url, {
          id: idArr,
          order_type: "1",
        })
        .then((res) => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    superBill() {
      var data = this.searchObj;
      data.order_type = 1;
      this.$http
        .post("/admin/bill/index.php?act=onlineBill&op=superBill", data)
        .then((res) => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    handleSelectionChange(val) {
      this.check = val;
    },
    //上传excel文件
    submit() {
      console.log(this.codeFileList[0].raw);
      if (this.codeFileList.length) {
        let data = new FormData();
        data.append("file", this.codeFileList[0].raw);
        this.$http
          .post(
            "/admin/adminImports/index.php?act=pointOrderSettleImport&op=run",
            data
          )
          .then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.dialogFormVisible = false;
              this.execlErr = res.data;
              if (this.execlErr.length > 0) {
                this.$alert(this.execlErr, "错误单号", {
                  confirmButtonText: "确定",
                  callback: (action) => {},
                });
              }
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((err) => {
            this.$message.error(err);
          });
      } else {
        alert("请选择文件");
      }
    },
    getListData() {
      var data = this.searchObj;
      data.page = this.searchContent.currentPage;
      data.pageSize = this.searchContent.pageSize;
      this.$http
          .get('/admin/points/index.php?act=PointsSettle&op=settleList&type=1', {
            params: data,
          })
        .then((res) => {
          if (res.code === 1) {
            this.total = res.data.totalCount;
            this.goodsList = res.data.list.map(item => {
              if(item.point_inner == 1) item.point_inner_checked = true
              else item.point_inner_checked = false
              return item
            })
            // this.$message.success( res.msg);
            // this.getListData();
          } else {
            this.total = 0;
            this.goodsList = [];
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    search() {
      this.searchContent.currentPage = 1;
      let order_time = this.searchContent.order_time;
      this.searchObj = objScreen({
        order_start_time: order_time[0] && parseInt(order_time[0].getTime() / 1000),
        order_end_time: order_time[1] && parseInt((order_time[1].getTime() / 1000+(24 * 60 * 60 - 1))),
        point_ordersn: this.searchContent.point_ordersn,
        point_buyername: this.searchContent.point_buyername,
        pgoods_name: this.searchContent.pgoods_name,
        pgoods_show: this.searchContent.pgoods_show,
        category_id: this.searchContent.category_id,
        pgoods_ifpay: this.searchContent.pgoods_ifpay,
        pgoods_brand: this.searchContent.pgoods_brand,
        pgoods_business_txt: this.searchContent.pgoods_business_txt,
        pgoods_travel: this.searchContent.pgoods_travel,
        pgoods_virtual: this.searchContent.pgoods_virtual,
        pgoods_serial: this.searchContent.pgoods_serial,
        point_inner: this.searchContent.point_inner,
        point_names: this.searchContent.point_names,
        member_mobile: this.searchContent.member_mobile,
        point_paymentcode: this.searchContent.point_paymentcode,
        point_orderstate: this.searchContent.point_orderstate,
        payed: this.searchContent.payed,
        is_bill: this.searchContent.is_bill,
        is_settled: this.searchContent.is_settled,
        originate: this.searchContent.originate,
        is_valid: this.searchContent.is_valid,
        is_flash: this.searchContent.is_flash,
        is_pt: this.searchContent.is_pt,
        exception_state: this.searchContent.exception_state
      });
      this.getListData();
    },
    getRefundStaus(staus) {
      let type = "info";
      let text = "退款";
      let disabled = true;
      switch (staus) {
        case 0:
          type = "primary";
          text = "退款";
          disabled = false;
          break;
        case 10:
          type = "info";
          text = "退款中";
          disabled = true;
          break;
        case 20:
          type = "info";
          text = "已退款";
          disabled = true;
          break;
        case 30:
          type = "info";
          text = "退款失败";
          disabled = true;
          break;
      }
      let a = {
        type,
        text,
        disabled,
      };
      return a;
    },

    getSettled(staus) {
      let text = "";
      if (staus == "0") {
        text = "结算";
      } else {
        text = "结算撤回";
      }
      return text;
    },

    updatesettle(id, staus, refund) {
      let settled;
      if (staus == 0) {
        if (refund == "10") {
          if (confirm("订单正在退款中，确实要结算吗？")) {
            settled = "1";
            this.jiesuanApi(id, settled);
          }
        } else {
          if (confirm("确定要结算吗？")) {
            settled = "1";
            this.jiesuanApi(id, settled);
          }
        }
      } else {
        if (confirm("确实要撤回结算吗？")) {
          settled = "0";
          this.jiesuanApi(id, settled);
        }
      }
    },

    jiesuanApi(id, settled) {
      this.$http
        .post(
          "/admin/pointprod/index.php?act=pointOrder&op=switchOrderSettleStatus",
          {
            point_orderid: id,
            settle_type: settled,
          }
        )
        .then((res) => {
          if (res.code == 0) {
            this.$message.success("修改成功！");
          } else {
            this.$message.error(res.msg);
          }
          this.getListData();
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

    resetSearchData() {
      // console.log(this.$refs);
      this.$refs["searchForm"].resetFields();
      this.searchContent.is_bill = "";
      this.searchContent.is_settled = "";
      this.search();
    },

    expertData() {
      var host;
      if (this.$store.state.isServer) {
        host = location.host.replace("admin", "api");
      } else {
        host = location.host + "/api";
      }
      var url =
        location.protocol +
        "//" +
        host +
        "/admin/pointprod/index.php?act=pointOrder&op=list&export=1";
      var searchData = this.searchObj;
      for (var key in searchData) {
        if (
          !(
            searchData[key] === null ||
            searchData[key] === "" ||
            searchData[key] === undefined ||
            key === "page" ||
            key === "pageSize" ||
            key === "currentPage"
          )
        ) {
          url += "&" + key + "=" + searchData[key];
        }
      }
      // console.log(url);
      window.location.href = url;
    },

    handleSizeChange(pageSize) {
      localStorage.setItem("pageSize", pageSize);
      this.searchContent.pageSize = pageSize;
      this.searchContent.currentPage = 1;
      this.getListData();
    },

    handleCurrentChange(page) {
      this.searchContent.currentPage = page;
      this.getListData();
    },

    buttonDeal(type, row) {
      switch (type) {
        case "showOrder":
          this.$refs.orderInfo.show_dialog_fn(row);
          break;
        case "add":
          this.$refs.updateDrawer.show_dialog_fn(row, 1);
          break;
        case "update":
          this.$refs.updateDrawer.show_dialog_fn(row);
          break;
        case "cancel":
          this.$confirm("确认取消兑换？").then((res) => {
            this.cancel(row)
          })
          break;
      }
    },

    cancel(row) {
      this.$http
        .post("/admin/pointprod/index.php?act=pointOrder&op=cancel", {
          orderId: row.point_orderid,
        })
        .then((res) => {
          if (res.code === 1) {
            row.point_orderstate = 2;
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

    bill(row) {
      this.$http
        .post("/admin/bill/index.php?act=onlineBill&op=bill", {
          id: row.point_orderid,
          order_type: "1",
        })
        .then((res) => {
          if (res.code === 1) {
            row.is_bill = "1";
            this.$message.success(res.msg);
          } else {
            this.$message.warning(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

    billRollback(row) {
      this.$http
        .post("/admin/bill/index.php?act=onlineBill&op=billRollback", {
          id: row.point_orderid,
          order_type: "1",
        })
        .then((res) => {
          if (res.code === 1) {
            row.is_bill = "0";
            this.$message.success(res.msg);
          } else {
            this.$message.warning(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
  },
  mounted() {
    resize(this);
  },
};
</script>
<style lang="scss" scoped>
.color-1 {
  color: #ff3300;
}
.bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-content-input {
  width: 200px;
}
.tpyeDown {
  color: #409eff;
  margin-top: 10px;
}
.logistics {
    /deep/.el-dialog {
      max-width: 680px;
    }
    .logisticsForm /deep/.el-upload--text{
      float: left;
      margin-right: 10px;
    }
}
</style>
